#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
移动端API测试脚本
用于测试移动端工单和材料API的认证和权限问题
"""

import requests
import json
import sys

# 服务器配置
BASE_URL = "http://localhost:5000/api"

def test_login():
    """测试登录功能"""
    print("\n=== 测试登录功能 ===")
    
    login_data = {
        "username": "18009981028",  # 使用日志中的用户
        "password": "123456"  # 默认密码
    }
    
    print(f"尝试登录用户: {login_data['username']}")
    
    try:
        response = requests.post(f"{BASE_URL}/auth/login", json=login_data)
        print(f"登录请求状态码: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            token = data.get('access_token')
            user = data.get('user')
            print(f"登录成功! 用户: {user.get('name', 'N/A')} ({user.get('role', 'N/A')})")
            print(f"用户区域: {user.get('area_name', 'N/A')}")
            return token, user
        else:
            print(f"登录失败: {response.text}")
            return None, None
            
    except Exception as e:
        print(f"登录请求异常: {e}")
        return None, None

def test_work_orders_api(token):
    """测试工单API"""
    print("\n=== 测试工单API ===")
    
    headers = {
        "Authorization": f"Bearer {token}"
    }
    
    # 测试获取工单列表
    params = {
        "per_page": 100,
        "area_filter": "true"
    }
    
    try:
        print(f"请求URL: {BASE_URL}/work-orders")
        print(f"请求参数: {params}")
        print(f"请求头: {headers}")
        
        response = requests.get(f"{BASE_URL}/work-orders", headers=headers, params=params)
        print(f"工单列表请求状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            data = response.json()
            work_orders = data.get('work_orders', [])
            print(f"成功获取工单列表，共 {len(work_orders)} 条工单")
            
            # 按状态统计
            status_count = {}
            for order in work_orders:
                status = order.get('status', 'unknown')
                status_count[status] = status_count.get(status, 0) + 1
            
            print("工单状态统计:")
            for status, count in status_count.items():
                print(f"  {status}: {count}")
                
        elif response.status_code == 403:
            print("权限不足 (403) - 用户可能没有访问工单的权限")
        elif response.status_code == 401:
            print("认证失败 (401) - Token可能无效或已过期")
        else:
            print(f"请求失败: {response.text[:500]}...")  # 只显示前500字符
            
    except Exception as e:
        print(f"工单API请求异常: {e}")

def test_materials_api(token):
    """测试材料API"""
    print("\n=== 测试材料API ===")
    
    headers = {
        "Authorization": f"Bearer {token}"
    }
    
    params = {
        "per_page": 1000
    }
    
    try:
        print(f"请求URL: {BASE_URL}/materials")
        print(f"请求参数: {params}")
        print(f"请求头: {headers}")
        
        response = requests.get(f"{BASE_URL}/materials", headers=headers, params=params)
        print(f"材料列表请求状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            data = response.json()
            materials = data.get('materials', [])
            print(f"成功获取材料列表，共 {len(materials)} 种材料")
            
            # 显示前5个材料
            if materials:
                print("前5个材料:")
                for i, material in enumerate(materials[:5]):
                    print(f"  {i+1}. {material.get('name', 'N/A')} ({material.get('unit', 'N/A')})")
                    
        elif response.status_code == 403:
            print("权限不足 (403) - 用户可能没有访问材料的权限")
        elif response.status_code == 401:
            print("认证失败 (401) - Token可能无效或已过期")
        else:
            print(f"请求失败: {response.text[:500]}...")  # 只显示前500字符
            
    except Exception as e:
        print(f"材料API请求异常: {e}")

def test_user_permissions(token, user):
    """测试用户权限"""
    print("\n=== 测试用户权限 ===")
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    user_id = user.get('id')
    if not user_id:
        print("无法获取用户ID")
        return
    
    # 检查用户权限
    permission_data = {
        "permission_codes": ["work_order.view", "material.view"]
    }
    
    try:
        response = requests.post(f"{BASE_URL}/permissions/users/{user_id}/check", 
                               headers=headers, json=permission_data)
        print(f"权限检查请求状态码: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            permissions = data.get('permissions', {})
            print("用户权限检查结果:")
            for perm, has_perm in permissions.items():
                print(f"  {perm}: {'✓' if has_perm else '✗'}")
        else:
            print(f"权限检查失败: {response.text}")
            
    except Exception as e:
        print(f"权限检查异常: {e}")

def main():
    """主函数"""
    print("移动端API测试脚本")
    print(f"测试服务器: {BASE_URL}")
    
    # 1. 测试登录
    token, user = test_login()
    if not token:
        print("\n❌ 登录失败，无法继续测试")
        sys.exit(1)
    
    # 2. 测试用户权限
    test_user_permissions(token, user)
    
    # 3. 测试工单API
    test_work_orders_api(token)
    
    # 4. 测试材料API
    test_materials_api(token)
    
    print("\n=== 测试完成 ===")

if __name__ == "__main__":
    main()